import { deepMix, each, wrapBehavior } from '@antv/util';
import { modifyCSS } from '@antv/dom-util';

class Toolbar {
    constructor(cfgs) {
        this._cfgs = deepMix(this.getDefaultCfg(), cfgs);
    }

    getDefaultCfg() {
        return { container: null };
    }

    get(key) {
        return this._cfgs[key];
    }
    set(key, val) {
        this._cfgs[key] = val;
    }
    // 初始化插件
    initPlugin(graph) {
        const self = this;
        this.set('graph', graph);
        const events = self.getEvents();
        const bindEvents = {};
        each(events, (v, k) => {
            const event = wrapBehavior(self, v);
            bindEvents[k] = event;
            graph.on(k, event); // 事件监听，更新toolbar
        });
        // 挂载到实例上
        this._events = bindEvents;

        this.initEvents();
        this.updateToolbar();
    }
    // 点击节点，命令执行后，更新toolbar
    getEvents() {
        return { 'after-node-selected': 'updateToolbar', aftercommandexecute: 'updateToolbar' };
    }
    // toolbar按钮点击，调用事件
    initEvents() {
        const graph = this.get('graph');
        const parentNode = this.get('container');
        const children = parentNode.querySelectorAll('.flow-toolbar > div[data-command]');
        each(children, child => {
            const cmdName = child.getAttribute('data-command');
            child.addEventListener('click', () => {
                // 如果此toolbar是启用状态
                if (graph.commandEnable(cmdName)) {
                    graph.executeCommand(cmdName);
                }
            });
        });
    }
    // 点击节点，命令执行后，更新toolbar
    updateToolbar() {
        const graph = this.get('graph');
        const parentNode = this.get('container');
        const children = parentNode.querySelectorAll('.flow-toolbar > div[data-command]');
        each(children, child => {
            const cmdName = child.getAttribute('data-command');
            // 按钮可被点击
            if (graph.commandEnable(cmdName)) {
                modifyCSS(child, {
                    cursor: 'pointer'
                });
                modifyCSS(child.children[0], {
                    fill: '#333',
                    cursor: 'pointer'
                });
                child.children[0].setAttribute('fill', '#333');
            // 按钮不可被点击
            } else {
                modifyCSS(child, {
                    cursor: 'default'
                });
                modifyCSS(child.children[0], {
                    fill: 'rgba(0, 0, 0, 0.25)',
                    cursor: 'default'
                });
                child.children[0].setAttribute('fill', 'rgba(0, 0, 0, 0.25)');
            }
        });
    }
    // 销毁插件
    destroyPlugin() {
        const graph = this.get('graph');
        graph.get('canvas').destroy();
        const container = graph.getContainer();
        container.parentNode.removeChild(container);
    }
}

export default Toolbar;
